﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Rodunu.Business.Models.Movies;

namespace Rodunu.Clients.WPF.Controls
{
    /// <summary>
    /// Interaction logic for Browse2d.xaml
    /// </summary>
    public partial class Browse2d : UserControl
    {
        private IList<Title> _titles;
        private int currentPosition;
        private ResourceDictionary internalResources;


        public Browse2d()
        {
            InitializeComponent();
            currentPosition = 0;
            internalResources = viewPort.Resources;
        }

        public void SetObjects(IList<Title> titles)
        {
            _titles = titles;
        }

        public void CreateObjects(int startPosition)
        {
            currentPosition = startPosition;
            if (_titles.Count > 0)
            {
                if ((startPosition - 1) >= 0)
                {
                    container.Children.Add(CreateModel(_titles[startPosition - 1].ImageUrl, "previous"));
                }
                container.Children.Add(CreateModel(_titles[startPosition].ImageUrl, "current"));
                if ((startPosition + 1) < _titles.Count)
                {
                    container.Children.Add(CreateModel(_titles[startPosition + 1].ImageUrl, "next"));
                }
            }
        }

        private ModelUIElement3D CreateModel(string imageUrl, string position)
        {
            if (imageUrl == null)
            {
                imageUrl = @"C:\Users\goodwins\Documents\Visual Studio 2008\Projects\Rodunu\Rodunu.Clients.WPF\images\NoImageAvailable.png";
            }

            VisualBrush vBrush = GetVisualBrush(imageUrl);

            ModelUIElement3D model3d = new ModelUIElement3D
            {
                Model = new GeometryModel3D
                {
                    Geometry = new MeshGeometry3D
                    {
                        TriangleIndices = new Int32Collection(new int[] { 0, 1, 2, 0, 2, 3 }),
                        TextureCoordinates = new PointCollection(new Point[] {new Point(0,1),
                                                                              new Point(1,1),
                                                                              new Point(1,0),
                                                                              new Point(0,0)}),
                        Positions = new Point3DCollection(new Point3D[] {new Point3D(-1, -1.5, 0),
                                                                         new Point3D(1, -1.5, 0),
                                                                         new Point3D(1, 1.5, 0),
                                                                         new Point3D(-1, 1.5, 0)})
                    },
                    Material = new DiffuseMaterial
                    {
                        Brush = CreateElementReflection(vBrush, 1.0)
                        //Brush = vBrush
                    },
                    BackMaterial = new DiffuseMaterial
                    {
                        Brush = Brushes.Black
                    },
                    Transform = CreateGroup(position)
                }
            };
            
            return model3d;
        }

        private VisualBrush CreateElementReflection(VisualBrush vBrush, double opacity)
        {
            double ElementWidth = 300.0;
            double ElementHeight = 300.0;


            Rectangle topRectangle = new Rectangle();
            topRectangle.Width = ElementWidth;
            topRectangle.Height = ElementHeight;
            topRectangle.Fill = new VisualBrush(vBrush.Visual);

            Rectangle bottomRectangle = null;
            Rectangle overlayRectangle = null;

            bottomRectangle = new Rectangle();
            bottomRectangle.Width = ElementWidth;
            bottomRectangle.Height = ElementHeight;
            VisualBrush brush = new VisualBrush(vBrush.Visual);
            brush.Transform = new ScaleTransform(1, -1, ElementWidth / 2, ElementHeight / 2);
            bottomRectangle.Fill = brush;
            Canvas.SetTop(bottomRectangle, ElementHeight);

            overlayRectangle = new Rectangle();
            overlayRectangle.Width = ElementWidth;
            overlayRectangle.Height = ElementHeight;
            overlayRectangle.Fill = internalResources["ReflectionBrush"] as Brush;
            Canvas.SetTop(overlayRectangle, ElementHeight);

            Canvas canvas = new Canvas();
            canvas.Width = ElementWidth;
            canvas.Height = ElementHeight * 2;
            canvas.Children.Add(topRectangle);
            canvas.Children.Add(bottomRectangle);
            canvas.Children.Add(overlayRectangle);

            return new VisualBrush { Visual = canvas, Opacity = opacity };
        }

        private Transform3DGroup CreateGroup(string position)
        {
            double xOffset = 0;
            double yOffset = 0;
            double zOffset = 0;

            if (position == "current")
            {
                xOffset = -1;
                yOffset = -1;
                zOffset = 0;
            }
            if (position == "next")
            {
                xOffset = 2;
                yOffset = 0;
                zOffset = -2;
            }
            if (position == "previous")
            {
                xOffset = -4;
                yOffset = 0;
                zOffset = -2;
            }

            Transform3DGroup group = new Transform3DGroup();
            group.Children.Add(new TranslateTransform3D
            {
                OffsetX = xOffset,
                OffsetY = yOffset,
                OffsetZ = zOffset
            });
            group.Children.Add(new RotateTransform3D
            {
                Rotation = new AxisAngleRotation3D
                {
                    Angle = 0,
                    Axis = new Vector3D(1, 0, 0)
                }
            });
            group.Children.Add(new ScaleTransform3D
            {
                ScaleX = 1.0,
                ScaleY = 1.0,
                ScaleZ = 1.0
            });

            return group;
        }

        private VisualBrush GetVisualBrush(string imageUrl)
        {
            Border border = new Border();
            border.Width = 15;
            border.Height = 15;
            border.CornerRadius = new CornerRadius(0.5);
            border.BorderThickness = new Thickness(0.5);
            border.BorderBrush = Brushes.WhiteSmoke;
            try
            {
                Image myImage = new Image
                {
                    Source = new BitmapImage(new Uri(@imageUrl, UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.Uniform,
                    Margin = new Thickness(0)
                };
                myImage.Width = myImage.Width * .5;
                border.Child = myImage;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(),"GetVisualBrush");
            }

            VisualBrush vBrush = new VisualBrush(border);

            return vBrush;
        }

        private void viewPort_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Right)
            {
                if ((currentPosition + 1) < _titles.Count)
                {
                    currentPosition += 1;
                    //run storyboard + 1;
                }
            }
            if (e.Key == Key.Left)
            {
                if ((currentPosition - 1) >= 0)
                {
                    currentPosition -= 1;
                    //run storyboard -1;
                }
            }
        }

        private void viewPort_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void viewPort_MouseDown(object sender, MouseButtonEventArgs e)
        {
            RayMeshGeometry3DHitTestResult clickedRayMeshResult = (RayMeshGeometry3DHitTestResult) VisualTreeHelper.HitTest(viewPort, e.GetPosition(viewPort));

            if (clickedRayMeshResult != null)
            {
                if (clickedRayMeshResult.ModelHit.Bounds.X == -2)
                {
                    //do current click event
                }
                if (clickedRayMeshResult.ModelHit.Bounds.X == 1)
                {
                    container.Children.Remove(clickedRayMeshResult.VisualHit);
                    

                }
                MessageBox.Show(clickedRayMeshResult.ModelHit.Bounds.ToString());
            }
        }

        private void viewPort_MouseMove(object sender, MouseEventArgs e)
        {

        }
    }
}
